package com.cskaoyan.service;

import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.wx.coupon.WxCouponExchangeBO;
import com.cskaoyan.bean.wx.coupon.WxCouponReceiveBO;
import com.cskaoyan.bean.wx.coupon.WxCouponSelectListVO;

import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * TODO   两个coupon合在一起，下面是WX
 *
 * @author makabaka
 * @date 2022-11-20 01:29
 */

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    @Override
    public CommonData<MarketCoupon> list(BasePageInfo basePageInfo, MarketCoupon marketCouponInfo) {
        //分页插件
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        //查询操作
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        //排序
        marketCouponExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        //拼接查询条件name=te&type=0&status=0
        if (marketCouponInfo.getName() != null) {
            criteria.andNameLike("%" + marketCouponInfo.getName() + "%");
        }
        if (marketCouponInfo.getType() != null) {
            criteria.andTypeEqualTo(marketCouponInfo.getType());
        }
        if (marketCouponInfo.getStatus() != null) {
            criteria.andStatusEqualTo(marketCouponInfo.getStatus());
        }
        //查看的是逻辑为删除的，deleted=0的
        criteria.andDeletedEqualTo(false);


        //查询
        List<MarketCoupon> marketCouponList = marketCouponMapper.selectByExample(marketCouponExample);
        //将查询结果作为有参构造方法的形参传入，可以获得PageInfo
        PageInfo<MarketCoupon> marketAdPageInfo = new PageInfo<>(marketCouponList);
        return CommonData.data(marketAdPageInfo);
    }

    @Override
    public MarketCoupon CouponCreate(MarketCoupon marketCouponinfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String temp = marketCouponinfo.getName();
        String format = sdf.format(new Date());
        try {
            Date time = sdf.parse(format);
            marketCouponinfo.setAddTime(time);
            marketCouponinfo.setUpdateTime(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //如果type类型是2则是兑换码券则需要生成兑换码
        String exchangeCode = getCode();
        if (marketCouponinfo.getType() == 2) {
            marketCouponinfo.setCode(exchangeCode);
        }
        //插入操作
        marketCouponMapper.insertSelective(marketCouponinfo);
        return marketCouponinfo;


    }

    @Override
    public MarketCoupon CouponUpdatePost(MarketCoupon marketCouponinfo) {
        //给更新时间赋值
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        try {
            Date time = sdf.parse(format);
            marketCouponinfo.setUpdateTime(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //当券变为了兑换码券且原先不是兑换码券则生成一个兑换码
        if (marketCouponinfo.getType() == 2 && marketCouponinfo.getCode() == null) {
            marketCouponinfo.setCode(getCode());
        }
        //构造更新时的where
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andIdEqualTo(marketCouponinfo.getId());
        //更新操作
        marketCouponMapper.updateByExampleSelective(marketCouponinfo, marketCouponExample);
        return marketCouponinfo;

    }

    @Override
    public boolean CouponDelete(MarketCoupon marketCoupon) {

        MarketCoupon marketCouponDelete = new MarketCoupon();
        marketCouponDelete.setDeleted(true);

        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andIdEqualTo(marketCoupon.getId());
        int deleteResult = marketCouponMapper.updateByExampleSelective(marketCouponDelete, marketCouponExample);
        if (deleteResult == 1) {
            return true;
        }
        return false;


    }

    @Override
    public CommonData<MarketCouponUser> CouponListUser(BasePageInfo basePageInfo, MarketCouponUser marketCouponUser) {
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        //用户id精确查询
        if (marketCouponUser.getUserId() != null) {
            criteria.andUserIdEqualTo(marketCouponUser.getUserId());
        }
        //status精确查询
        if (marketCouponUser.getStatus() != null) {
            criteria.andStatusEqualTo(marketCouponUser.getStatus());
        }
        criteria.andCouponIdEqualTo(marketCouponUser.getCouponId());
        //查看的为逻辑删除的,deleted=0
        criteria.andDeletedEqualTo(false);
        marketCouponUserExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        PageInfo<MarketCouponUser> marketCouponUserPageInfo = new PageInfo<>(marketCouponUsers);
        return CommonData.data(marketCouponUserPageInfo);


    }

    @Override
    public MarketCoupon CouponRead(Integer id) {
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(id);
        return marketCoupon;

    }

    private String getCode() {
        String code = UUID.randomUUID().toString();
        return code;
    }

    /*
     * @Author makabaka
     * @Description //TODO   下面是WX
     * @Date 10:29 2022/11/22
     * @Param   status=0&page=1&limit=10
     * @return
     **/

    @Override
    public CommonData wxCouponMylist(BasePageInfo basePageInfo, short status) {

        //获取id 用shiro  等着补
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        if (marketUser == null || marketUser.getId() == null) {
            return null;
        }
        Integer userId = marketUser.getId();
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            Date date = new Date();
            if(marketCouponUser.getEndTime().getTime()<date.getTime()){
                marketCouponUser.setStatus((short) 2);
                marketCouponUser.setUsedTime(new Date());
                int i = marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);

                // int i=marketCouponUserMapper.updateById(marketCouponUser.getId());
            }

        }
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        List<WxCouponSelectListVO> marketCouponList = marketCouponMapper.selectwxCouponlist(userId, status);

        PageInfo<WxCouponSelectListVO> wxCouponSelectListVOPageInfo = new PageInfo<>(marketCouponList);
        return CommonData.data(wxCouponSelectListVOPageInfo);


    }

    @Override
    public boolean wxCouponReceive(WxCouponReceiveBO wxCouponReceiveBO) {

        Integer couponId = wxCouponReceiveBO.getCouponId();
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        if (marketCoupon.getType() == 0) {
            return receiveCoupon(couponId);
        }
        return false;
    }

    @Override
    public CommonData wxCouponList(BasePageInfo basePageInfo) {

        //limit如果没有就默认10
        if (basePageInfo.getLimit() == null) {
            basePageInfo.setLimit(10);
        }
        //page如果没有就默认1
        if (basePageInfo.getPage() == null) {
            basePageInfo.setPage(1);
        }
        //开启分页插件
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        //order如果没有就默认desc
        if (basePageInfo.getOrder() == null) {
            basePageInfo.setOrder("desc");
        }
        //sort如果没有就默认add_time
        if (basePageInfo.getSort() == null) {
            basePageInfo.setSort("add_time");
        }
        //sql查询--查询没有被删除的优惠券信息
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        criteria.andDeletedEqualTo(false);

        //--status为0的
        criteria.andStatusEqualTo((short) 0);

        //应该是通用券---------------------------------注册和兑换的应该隐藏---------------------
        criteria.andTypeEqualTo((short) 0);
        //应该是还有的----------------------------无限券为0，有限券不少于2
        criteria.andTotalNotEqualTo(1);

        marketCouponExample.setOrderByClause(basePageInfo.getSort() + " " + basePageInfo.getOrder());
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        //以有参形式放入到分页插件
        PageInfo<MarketCoupon> marketCouponPageInfo = new PageInfo<>(marketCoupons);
        //封装结果
        return CommonData.data(marketCouponPageInfo);


    }

    /*
     * @Author makabaka
     * @Description //TODO
     * @Date 15:08 2022/11/22
     * @Param       {"errno":740,"errmsg":"优惠券已兑换"}  {"errno":742,"errmsg":"优惠券不正确"}
     * @return      {"errno":0,"errmsg":"成功"}
     **/

    @Override
    public int wxCouponExChange(WxCouponExchangeBO wxCouponExchangeBO) {
        if (wxCouponExchangeBO == null || wxCouponExchangeBO.getCode() == null) {
            return 742;
        }
        //兑换码
        String code = wxCouponExchangeBO.getCode();
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
        //兑换券
        short type = 2;
        criteria.andCodeEqualTo(code);
        criteria.andTypeEqualTo(type);
        criteria.andDeletedEqualTo(false);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        if (marketCoupons.size() == 1) {
            boolean result = receiveCoupon(marketCoupons.get(0).getId());
            if (result) {
                return 0;
            }
        }
        return 401;

    }

    @Override
    public CommonData   wxCouponSelectlist(Integer cartId, Integer grouponRulesId) {
        //shiro获取userId;
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        if (marketUser == null || marketUser.getId() == null) {
            return null;
        }
        Integer userId = marketUser.getId();


        BigDecimal orderPriceSum = new BigDecimal(0);
        if (cartId != 0) {
            //对应立即下单的情况--找到该条cart记录
            //Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            MarketCart marketCartInfo = (MarketCart) session.getAttribute("fastAdd");
            //计算订单总金额以作为可用优惠券的一个筛选条件
            BigDecimal price = marketCartInfo.getPrice();
            Short number = marketCartInfo.getNumber();
            BigDecimal numberToBigDecimal = new BigDecimal(number);
            orderPriceSum = price.multiply(numberToBigDecimal);
        } else {
            //cartId为0
            //计算该订单价格orderPriceSum--；满足条件的记录的商品货品价格*货品数量 之和
            //在购物车商品表中查询该用户id对应的商品记录列表----该用户id、未删除、已选择、的
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andDeletedEqualTo(false);
            criteria.andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);
            //计算订单总额
            for (MarketCart marketCart : marketCarts) {
                //获取 价格
                BigDecimal price = marketCart.getPrice();
                //获取数量
                Short number = marketCart.getNumber();
                BigDecimal numberToBigDecimal = new BigDecimal(number);
                //计算该条记录的价格总和
                BigDecimal cartPriceSum = price.multiply(numberToBigDecimal);
                //订单综合加和
                orderPriceSum = orderPriceSum.add(cartPriceSum);
            }
        }
        //查询--该用户id、未删除、未使用、在使用时间内、满足满减条件的优惠券列表
        List<WxCouponSelectListVO> myCouponListByOrderPriceSum = getMyCouponListByOrderPriceSum(orderPriceSum, userId, "discount desc");
        CommonData<WxCouponSelectListVO> wxCouponSelectlistVoCommonData = new CommonData<>();
        wxCouponSelectlistVoCommonData.setList(myCouponListByOrderPriceSum);
        wxCouponSelectlistVoCommonData.setTotal(myCouponListByOrderPriceSum.size());
        wxCouponSelectlistVoCommonData.setLimit(myCouponListByOrderPriceSum.size());
        wxCouponSelectlistVoCommonData.setPage(1);
        wxCouponSelectlistVoCommonData.setPages(1);
        return wxCouponSelectlistVoCommonData;
    }

    /*
     * @Author makabaka
     * @Description //TODO   根据submit传过来的couponId 修改coupon状态
     * @Date 17:58 2022/11/24
     * @Param
     * @return
     **/

    @Override
    public void wxCoupobUserBy(Integer useCouponId) {
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setId(useCouponId);
        marketCouponUser.setStatus((short) 1);
        marketCouponUser.setUsedTime(new Date());
        int i = marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);

    }


    private List<WxCouponSelectListVO> getMyCouponListByOrderPriceSum(BigDecimal orderPriceSum, Integer userId, String order) {
        //查询--该用户id、未删除、未使用、在使用时间内、满足满减条件的优惠券列表
        List<WxCouponSelectListVO> couponInfoList = marketCouponUserMapper.selectByUserIdAndOrderPriceSum(orderPriceSum, userId, order);
        return couponInfoList;
    }


    /*
     * @Author makabaka
     * @Description //TODO [couponId]
     * @Date 14:45 2022/11/22
     * @Param [couponId]
     * @return
     **/
    private boolean receiveCoupon(Integer couponId) {
        //根据优惠券id获取对应的优惠券信息
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
        //根据优惠券信息进行有效性校验--status是否为0 delete位是否为0，
        if (marketCoupon.getStatus() != 0 || marketCoupon.getDeleted() != false) {
            return false;
        }
        //根据优惠券信息进行有效性校验--券总数是否是无限或够减(默认要留一张防止变化为无限量)
        if (marketCoupon.getTotal() != 0) {
            //进到这说明不是无限量
            if (marketCoupon.getTotal() < 2) {
                //不够减了
                return false;
            }
        }
        //获取当前用户id------------- 拿到userId和couponId 对两个表进行筛选
        Subject subject = SecurityUtils.getSubject();
        MarketUser marketUser = (MarketUser) subject.getPrincipal();
        Integer userId = marketUser.getId();

        //校验通过后，当优惠券领取次数有限时，获取此优惠券couponId此用户userId在优惠券使用表中的对应券数是否能再领
        if (marketCoupon.getLimit() != 0) {
            //走到这说明该优惠券每人限领
            //查看该用户领过多少张---过期的券算，使用过的算，删除的也算
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria = marketCouponUserExample.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andCouponIdEqualTo(couponId);
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            //用户持有的该券数目大于等于该券所限制的则不予领取
            if (marketCouponUsers.size() >= marketCoupon.getLimit()) {
                return false;
            }
        }
        //能领时进行领取处理---优惠券表中若该优惠券不是不限量则先减一张；对应的再在用户优惠券表中添加一个记录--注意添加时间和更新时间
        if (marketCoupon.getTotal() != 0) {
            //说明是有总量限制的-1
            MarketCoupon marketCouponForUpdate = new MarketCoupon();
            marketCouponForUpdate.setTotal(marketCoupon.getTotal() - 1);
            marketCouponForUpdate.setId(couponId);
            //这里领取时不更新时间了，只更新总数
            MarketCouponExample marketCouponExample = new MarketCouponExample();
            MarketCouponExample.Criteria criteria = marketCouponExample.createCriteria();
            criteria.andIdEqualTo(couponId);
            int effectRowsOfUpdateMarketCoupon = marketCouponMapper.updateByExampleSelective
                    (marketCouponForUpdate, marketCouponExample);
            if (effectRowsOfUpdateMarketCoupon != 1) {
                return false;
            }
        }
        //走到这里可以进行领取了--优惠券用户使用表添加一条数据
        MarketCouponUser marketCouponUser = new MarketCouponUser();
        marketCouponUser.setUserId(userId);
        marketCouponUser.setCouponId(couponId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        try {
            //添加时间和更新时间
            Date time = sdf.parse(format);
            marketCouponUser.setAddTime(time);
            marketCouponUser.setUpdateTime(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //  `time_type` smallint(6) DEFAULT '0' COMMENT '有效时间限制，
        //  如果是0，则基于领取时间的有效天数days；如果是1，则start_time和end_time是优惠券有效期；',
        if (marketCoupon.getTimeType() == 1) {
            //走到这说明是绝对日期有效的兑换券
            marketCouponUser.setStartTime(marketCoupon.getStartTime());
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
        }
        if (marketCoupon.getTimeType() == 0) {
            //走到这说明是领取相对时间的优惠券
            //开始时间和获取时间相同，结束时间为开始时间+days
            marketCouponUser.setStartTime(marketCoupon.getAddTime());
            Date endDate = addDay(marketCoupon.getAddTime(), marketCoupon.getDays());
            marketCouponUser.setEndTime(endDate);
        }
        int insertSelective = marketCouponUserMapper.insertSelective(marketCouponUser);
        if (insertSelective != 1) {
            return false;
        }
        return true;
    }


    public Date addDay(Date date, int i) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, i);
        Date newDate = c.getTime();
        return newDate;
    }


}
